package com.sam.widget.text_view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;

import com.sam.widget.R;

public class StateTextView extends CustomFontTextView {
    private GestureDetector gestureDetector;
    private int bgFilterColor = Color.GRAY;
    public StateTextView(Context context) {
        this(context,null);
    }

    public StateTextView(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }
    public StateTextView(final Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.StateTextView);
        bgFilterColor = ta.getColor(R.styleable.StateTextView_bgFilterColor, bgFilterColor);
        ta.recycle();

        gestureDetector = new GestureDetector(context, onGestureListener);
    }

    private void addFilter(){
        if(getBackground() == null) return;
        getBackground().setColorFilter(bgFilterColor, PorterDuff.Mode.MULTIPLY);
    }

    private void removeFilter(){
        if(getBackground() == null) return;
        getBackground().clearColorFilter();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_CANCEL){
            removeFilter();
        }
        return gestureDetector.onTouchEvent(event);
    }



    private GestureDetector.OnGestureListener onGestureListener = new GestureDetector.OnGestureListener() {
        @Override
        public boolean onDown(MotionEvent e) {
            addFilter();
            return true;
        }

        @Override
        public void onShowPress(MotionEvent e) {

        }

        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            removeFilter();
            performClick();
            return false;
        }

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            return false;
        }

        @Override
        public void onLongPress(MotionEvent e) {
            removeFilter();
            performLongClick();
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            return false;
        }
    };
}
